<template>
  <div class="recording-list">
    <!-- 搜索筛选区域 -->
    <el-card class="filter-card">
      <el-row :gutter="12" type="flex" align="bottom">
        <el-col :span="6">
          <el-input
            v-model="recordingSearchKeyword"
            placeholder="请输入搜索关键词"
            prefix-icon="Search"
            clearable
            @keyup.enter="handleRecordingSearch"
          />
        </el-col>
        <el-col :span="7">
          <el-date-picker
            v-model="recordingDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleRecordingDateChange"
          />
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="streamFilter"
            placeholder="选择直播流"
            clearable
            @change="handleRecordingSearch"
          >
            <el-option
              v-for="stream in streams"
              :key="stream.id"
              :label="stream.name"
              :value="stream.id"
            />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select
            v-model="taskFilter"
            placeholder="选择任务"
            clearable
            @change="handleRecordingSearch"
          >
            <el-option
              v-for="task in tasks"
              :key="task.id"
              :label="task.name"
              :value="task.id"
            />
          </el-select>
        </el-col>
        <el-col :span="2" class="text-right">
          <el-button type="primary" @click="handleRecordingSearch">搜索</el-button>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 录制列表 -->
    <el-table
      v-loading="recordingLoading"
      :data="displayedRecordings"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600', fontSize: '13px' }"
    >
      <el-table-column label="直播流" width="200" show-overflow-tooltip>
        <template #default="scope">
          <div>
            <div>{{ scope.row.stream_name || '-' }}</div>
            <div style="font-size: 12px; color: #909399;">{{ scope.row.stream_id || '-' }}</div>
            <div style="font-size: 12px; color: #909399; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ scope.row.name || '-' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="截图" width="80" align="center">
        <template #default="scope">
          <el-image
            :src="scope.row.screenshot_url || '/default-screenshot.jpg'"
            :preview-src-list="[scope.row.screenshot_url || '/default-screenshot.jpg']"
            style="width: 60px; height: 40px; object-fit: cover; border-radius: 4px;"
            placeholder="截图"
            @error="onImageError"
          />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)" size="small">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="录制时间" width="200" show-overflow-tooltip>
        <template #default="scope">
          <div>
            <div>开始: {{ formatDateTime(scope.row.start_time) }}</div>
            <div v-if="scope.row.status !== 'recording'">结束: {{ formatDateTime(scope.row.end_time) }}</div>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column label="文件大小" width="100" align="center">
        <template #default="scope">
          {{ formatFileSize(scope.row.size) }}
        </template>
      </el-table-column>
      <el-table-column label="时移回看" width="220" show-overflow-tooltip>
        <template #default="scope">
          <div>
            <div 
              v-if="scope.row.recording_url"
              class="playable-url"
              @click="playVideo(scope.row)"
              style="font-size: 12px; color: #1890ff; text-decoration: underline; word-break: break-all; cursor: pointer;"
            >
              {{ scope.row.recording_url }}
            </div>
            <div v-else>-</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="录制文件" width="120" align="center">
        <template #default="scope">
          <el-button
            size="small"
            type="success"
            circle
            plain
            @click="showFileList(scope.row)"
            title="点击显示详情"
          >
            {{ scope.row.file_count || 0 }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="信息" width="200" show-overflow-tooltip>
        <template #default="scope">
          <div>
            <div>{{ scope.row.encoding_info || '-' }}</div>
            <div>{{ scope.row.resolution || '-' }}</div>
            <div>{{ scope.row.bitrate || '-' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="文件位置" width="220" show-overflow-tooltip>
        <template #default="scope">
          <div>
            <div>节点ID: {{ scope.row.node_id || '-' }}</div>
            <div>IP: {{ scope.row.node_ip || '-' }}</div>
            <div style="font-size: 12px; color: #909399; word-break: break-all;">{{ scope.row.path || '-' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right" align="center">
        <template #default="scope">
          <div class="action-cell">
            <el-button-group>
              <el-tooltip content="播放" placement="top">
                <el-button 
                  size="small" 
                  type="primary" 
                  :icon="VideoPlay" 
                  circle
                  plain
                  @click="playVideo(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="拆条" placement="top">
                <el-button 
                  size="small" 
                  type="warning" 
                  :icon="Scissor" 
                  circle
                  plain
                  @click="router.push({ name: 'RecordingClippingPage', params: { id: scope.row.id } })"
                />
              </el-tooltip>
              <el-tooltip content="详情" placement="top">
                <el-button 
                  size="small" 
                  type="info" 
                  :icon="InfoFilled" 
                  circle
                  plain
                  @click="showInfo(scope.row)"
                />
              </el-tooltip>
            </el-button-group>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="recordingCurrentPage"
        v-model:page-size="recordingPageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecordings"
        @size-change="handleRecordingSizeChange"
        @current-change="handleRecordingCurrentChange"
      />
    </div>
  </div>

  <!-- 播放器弹窗组件 -->
  <VideoPlayerDialog 
    :show-player="showPlayer" 
    :current-video="currentVideo" 
    @update:showPlayer="handleShowPlayerUpdate"
    @close="handlePlayerClose"
    @ready="handlePlayerReady"
    @error="handlePlayerError"
  />
</template>

<script setup>
import { useRecordingClipping } from './useRecordingClipping'
import { VideoPlay, VideoPause, Scissor, Folder, InfoFilled } from '@element-plus/icons-vue'
import VideoPlayerDialog from './VideoPlayerDialog.vue'
import { useRouter } from 'vue-router'

// 使用录制拆条功能钩子
const router = useRouter()
const {
  recordingLoading,
  recordings,
  streams,
  tasks,
  recordingSearchKeyword,
  recordingDateRange,
  streamFilter,
  taskFilter,
  recordingCurrentPage,
  recordingPageSize,
  totalRecordings,
  displayedRecordings,
  getStatusType,
  getStatusText,
  formatDateTime,
  formatFileSize,
  handleRecordingSearch,
  handleRecordingDateChange,
  handleRecordingSizeChange,
  handleRecordingCurrentChange,
  playVideo,
  startClip,
  showFileList,
  toggleRecording,
  showInfo,
  showPlayer,
  currentVideo
} = useRecordingClipping()

// 处理图片加载错误
const onImageError = (e) => {
  e.target.src = '/default-screenshot.jpg'
}

// 格式化时长
const formatDuration = (seconds) => {
  if (!seconds) return '00:00:00'
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
}

// 处理播放器关闭事件
const handlePlayerClose = () => {
  console.log('播放器弹窗已关闭')
}

// 处理播放器准备就绪事件
const handlePlayerReady = () => {
  console.log('播放器准备就绪')
}

// 处理播放器错误事件
const handlePlayerError = (error) => {
  console.error('播放器播放出错', error)
}

// 处理播放器显示状态更新
const handleShowPlayerUpdate = (value) => {
  console.log('播放器显示状态更新', value)
  // showPlayer 状态是从 useRecordingClipping 钩子中解构出来的
  // 这里不需要额外赋值，因为 Vue 3 的响应式系统会自动处理
}

</script>

<style scoped>
.recording-list {
  width: 100%;
}

.filter-card {
  margin-bottom: 5px;
  padding: 2px; 
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.action-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}

.action-cell .el-button-group {
  display: flex;
  gap: 2px;
}

.action-cell .el-button {
  width: 24px;
  height: 24px;
  padding: 4px;
  transition: all 0.2s ease;
}

.action-cell .el-button:hover {
  transform: scale(1.1);
}

/* 表格样式优化 */
.el-table {
  width: 100% !important;
}

.el-table :deep(.el-table__body tr) {
  height: 45px;
}

.el-table :deep(.el-table__body td) {
  vertical-align: middle;
}
</style>